package com.np.rtmpdump1;

import android.media.projection.MediaProjection;
import android.util.Log;

import java.util.concurrent.LinkedBlockingDeque;

/**
 * 发送层，耗时操作，所以让他继承 Thread
 */
public class ScreenLive extends Thread {
    private static final String TAG = "well";

    static {
        System.loadLibrary("native-lib");
    }

    private boolean isLiving;
    private String url;
    private MediaProjection mediaProjection;
    private LinkedBlockingDeque<RTMPPackage> queue = new LinkedBlockingDeque<>();   // 生产者消费者模式的队列

    public void startLive(String url, MediaProjection mediaProjection) {
        this.url = url;
        this.mediaProjection = mediaProjection;

        // 调用线程的 start() 方法，然后执行线程的 run() 方法
        start();
    }

    public void addPackage(RTMPPackage rtmpPackage) {
        if (isLiving) {
            queue.add(rtmpPackage);
        }
    }

    @Override
    public void run() {
        // 连接 RTMP 服务器
        if (!connect(url)) {
            Log.i(TAG, "run:--------->连接失败");
            return;
        }

        VideoCodec videoCodec = new VideoCodec(this);
        videoCodec.startLive(this.mediaProjection);

        RTMPPackage rtmpPackage = null;
        try {
            rtmpPackage = queue.take();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Log.i(TAG, "取出数据");
        if (rtmpPackage != null && rtmpPackage.getBuffer() != null && rtmpPackage.getBuffer().length > 0) {
            Log.i(TAG, "run:---------->推送" + rtmpPackage.getBuffer().length);

            // 一帧一帧发送
            sendData(rtmpPackage.getBuffer(), rtmpPackage.getBuffer().length, rtmpPackage.getTms());
        }
    }

    private native boolean connect(String url);

    private native boolean sendData(byte[] data, int len, long tms);
}
